import axios from '@/util/axios';
// import 
import config from '@/config';

import { ElLoading } from 'element-plus'


const baseUrl = config.baseUrl;

// request.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'


const service = axios.create({
    baseURL: baseUrl, // 设置请求的基本URL
    //timeout: 5000, // 请求超时时间
    withCredentials: true, //表示跨域请求时是否需要使用凭证
  })
const redirect = function () {
  const local = location.origin
  location.replace( baseUrl + "/security/oauth2/authorize?client_id=cloudcentral&scope=openid+profile+phone&response_type=code&redirect_uri=" + local)
}


const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.0)',
  })
  // setTimeout(() => {
  //   loading.close()
  // }, 2000)
  return loading; 
}

let loadingInstance = openFullScreen(); 
service.interceptors.request.use(
  config => {
    let tokenData = localStorage.getItem('TOKENDATA');
    loadingInstance = openFullScreen(); 
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    if (tokenData) {
      tokenData = JSON.parse(tokenData)
      config.headers['Authorization'] = tokenData.token_type + ' ' + tokenData.access_token
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)
service.interceptors.response.use(response => {
  loadingInstance.close();
  if (response.data.code == 401) {
    redirect()
    return Promise.reject(response)
  } else return response
}, error => {
  // if (error.response.status == 401) redirect()
  Promise.reject(error)
})


let Urequest = {
  post: (url, data) => {
    return new Promise((resolve, reject) => {
      service.post(baseUrl + url, data)
        .then(res => {
          resolve(res);

        })
        .catch(err => {
          reject(err.data)
        })
    });
  },
  put: (url, data) => {
    return new Promise((resolve, reject) => {
      service.put(baseUrl + url, data)
        .then(res => {
          resolve(res);
        })
        .catch(err => {
          reject(err.data)
        })
    });
  },
  delete: (url, params) => {

    return new Promise((resolve, reject) => {
      service.delete(baseUrl + url, {
        params: params
      })
        .then(res => {
          resolve(res);
        })
        .catch(err => {
          reject(err.data)
        })
    });
  },
  get: (url, params) => {
    return new Promise((resolve, reject) => {
      service.get(baseUrl + url, {
        params: params
      }).then(res => {
        resolve(res);

      }).catch(err => {
        reject(err.data)
      })
    });
  }
}

export default Urequest;


